<?php

namespace Admin\Controller;

use Utuo\BackgroundController;

/**
 * wmfl.cn version 5.0
 * -----------------------------------------------
 * @author esinger <esinger@qq.com>
 * @link http://www.utuo88.com
 * @copyright 2014 Utuo Tech co.,Ltd
 */

/**
 * 后台菜单管理
 */
class MenuController extends BackgroundController {
	// 初始化
	public function _initialize() {
		$this->setControllerTitle('菜单管理');
		$this->setActionTitle(array(
				'index' => '菜单列表',
				'add' => '添加菜单',
				'modify' => '修改菜单',
				'recycle' => '回收站'
		));
		$this->setActionNav(array(
				'index',
				'add',
				'recycle'
		));
		$topMenuLists = M('menu')->where('pid=0 AND is_deleted=0')->getField('id,name');
		$this->setLinkNavTitle('菜单分类');
		$this->setLinkNav('顶级菜单', U('Admin/Menu/index'));
		foreach ($topMenuLists as $id => $name) {
			$this->setLinkNav($name, U('Menu/index?pid=' . $id));
		}
	}
	
	// 菜单列表
	public function indexAction() {
		$this->getMenuList(0);
	}
	
	// 回收站
	public function recycleAction() {
		$this->getMenuList(1);
	}
	
	// 获取列表
	private function getMenuList($is_deleted) {
		$page = $this->getPage();
		$pagesize = $this->getPageSize();
		$pid = I('pid', 0, 'intval');
		$condition = array(
				'is_deleted' => $is_deleted,
				'pid' => $pid
		);
		$menuLists = M('menu')->where($condition)->limit($pagesize)->page($page)->order('sort')->select();
		$menuCount = M('menu')->where($condition)->count();
		$this->assign('menuLists', $menuLists);
		$this->showPage($menuCount, $pagesize);
		$this->display();
	}
	
	// 添加菜单
	public function addAction() {
		$topMenu = M('menu')->where('pid=0 AND is_deleted=0')->getField('id,name');
		$topMenuOptions = $this->getOption($topMenu, null, '顶级菜单');
		$this->assign('topMenuOptions', $topMenuOptions);
		$this->display();
	}
	
	// 提交添加
	public function addPostAction() {
		if (M('menu')->create()) {
			if (M('menu')->add()) {
				$this->ajaxSuccess('添加菜单成功');
			} else {
				$this->ajaxError('添加菜单失败');
			}
		} else {
			$this->ajaxError('创建数据失败');
		}
	}
	
	// 修改菜单
	public function modifyAction() {
		$id = I('id', 0, 'intval');
		$menu = M('menu')->getById($id);
		$topMenuOptions = M('menu')->where('pid=0 AND is_deleted=0')->getField('id,name');
		$this->assign('topMenuOptions', $this->getOption($topMenuOptions, $menu['pid'], '顶级菜单'));
		$this->assign('menu', $menu);
		$this->display();
	}
	
	// 提交修改菜单
	public function modifyPostAction() {
		if (M('menu')->create()) {
			if (M('menu')->save()) {
				$this->ajaxSuccess('修改菜单成功');
			} else {
				$this->ajaxError('修改菜单失败');
			}
		} else {
			$this->ajaxError('创建数据失败');
		}
	}
	
	// 移除菜单
	public function removePostAction() {
		$this->ajaxRemove('menu');
	}
	
	// 恢复菜单
	public function restorePostAction() {
		$this->ajaxRestore('menu');
	}
	
	// 彻底删除
	public function deletePostAction() {
		$this->ajaxDelete('menu');
	}
}
 
// End of file MenuController.class.php
